// Infrastructure/Repositories/FileRepository.cs
using Microsoft.EntityFrameworkCore;
using UniversalAdmin.Domain.Repositories;
using UniversalAdmin.Infrastructure.Data;
using File = UniversalAdmin.Domain.Entities.File;

namespace UniversalAdmin.Infrastructure.Repositories;

public class FileRepository : BaseRepository<File>, IFileRepository
{
  public FileRepository(UniversalAdminDbContext context) : base(context) { }

  public async Task<IEnumerable<File>> GetFilesByUserIdAsync(int userId)
  {
    return await _context.Files
        .Where(f => f.UserId == userId)
        .OrderByDescending(f => f.CreatedAt)
        .ToListAsync();
  }

  public async Task<(IEnumerable<File> Items, int TotalCount)> SearchFilesAsync(
      string? keyword = null,
      string? mimeType = null,
      int? userId = null,
      string? userName = null,
      int pageIndex = 1,
      int pageSize = 10)
  {
    IQueryable<File> query = _context.Files.Include(f => f.User);

    if (!string.IsNullOrWhiteSpace(keyword))
    {
      query = query.Where(f =>
          f.Name.Contains(keyword) ||
          f.OriginalName.Contains(keyword));
    }

    if (!string.IsNullOrWhiteSpace(mimeType))
    {
      query = query.Where(f => f.MimeType == mimeType);
    }

    if (userId.HasValue)
    {
      query = query.Where(f => f.UserId == userId.Value);
    }

    var totalCount = await query.CountAsync();

    var items = await query
        .OrderByDescending(f => f.CreatedAt)
        .Skip((pageIndex - 1) * pageSize)
        .Take(pageSize)
        .AsNoTracking()
        .ToListAsync();

    return (items, totalCount);
  }

  public async Task<long> GetTotalStorageUsageAsync()
  {
    return await _context.Files.SumAsync(f => f.Size);
  }

  public async Task<long> GetUserStorageUsageAsync(int userId)
  {
    return await _context.Files
        .Where(f => f.UserId == userId)
        .SumAsync(f => f.Size);
  }
}